package cn.hznc.controller.service.testTask;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.constant.CommonConstant;
import cn.hznc.domain.entity.ToolForkInfoEntity;
import cn.hznc.domain.entity.TypeItemEntity;
import cn.hznc.mapper.ICabinetRecordMapper;
import cn.hznc.mapper.ToolForkInfoMapper;
import cn.hznc.mapper.TypeItemMapper;
import cn.hznc.repository.TypeItemRepository;
import cn.hznc.utils.CommonUtil;
import cn.hznc.vo.CategoryVo;
import cn.hznc.vo.typeitem.TypeItemVo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author：Administrator
 * @Date：2023/10/26 14:22
 */
@Service
@Slf4j
public class TestTaskService{

    @Resource
    private ToolForkInfoMapper toolForkInfoMapper;

    @Resource
    private ICabinetRecordMapper iCabinetRecordMapper;

    @Resource
    private TypeItemRepository typeItemRepository;

    @Resource
    private TypeItemMapper typeItemMapper;



//    public Integer getByICabinetRecord(GetByICabinetRecordReq getByICabinetRecordReq) throws ParseException {
//        Map<String, Object> contentMap = new HashMap<>();
//        contentMap.put("Uid", "");
//        contentMap.put("Code", UrlConstant.ICABINET_FEEDING_SYNC_CODE);
//        contentMap.put("Digest", CommonConstant.ICABINET_DIGEST);
//        //请求参数data
//        Map<String, Object> dataMap = new HashMap<>();
//        if(ObjectUtil.isNull(getByICabinetRecordReq.getFlag())){
//            getByICabinetRecordReq.setFlag(true);
//        }
//        if(getByICabinetRecordReq.getFlag()){
//            dataMap.put("Gtype", UrlConstant.ICABINET_FEEDING_SYNC_GTYPE);
//        }else {
//            dataMap.put("Gtype", UrlConstant.ICABINET_RECLAIMING_SYNC_GTYPE);
//        }
//        //获取时间map
//        if (ObjectUtil.isNull(getByICabinetRecordReq.getStartTime())) {
//            Map<String, String> dateMap = CommonUtil.minusTime24h();
//            dataMap.put("Date1", dateMap.get("Date1"));
//            dataMap.put("Date2", dateMap.get("Date2"));
//            contentMap.put("Data", JSONObject.toJSONString(dataMap));
//        } else {
//            dataMap.put("Date1", getByICabinetRecordReq.getStartTime());
//            dataMap.put("Date2", getByICabinetRecordReq.getEndTime());
//            contentMap.put("Data", JSONObject.toJSONString(dataMap));
//        }
//        String post = HttpUtil.post(UrlConstant.ICABINET_FEEDING_SYNC_URL, contentMap);
//        //String post = CommonUtil.postMap(UrlConstant.ICABINET_FEEDING_SYNC_URL , heardMap , contentMap);
//        if (StringUtil.isNotEmpty(post)) {
//            JSONObject jsonObject = JSONObject.parseObject(post);
//            if (jsonObject.get("success").equals(true)) {
//                Object o = jsonObject.get("data");
//                JSONArray dataArray = JSONArray.parseArray(o.toString());
//                List<Map<String , Object>> retList = new ArrayList<>();
//                for (Object oneRecordObject : dataArray) {
//                    JSONArray oneRecord = JSONArray.parseArray(oneRecordObject.toString());
//                    if(oneRecord.get(10).toString().equals(getByICabinetRecordReq.getToolType())) {
//                        Map<String , Object> paramMap = new HashMap<>();
//                    }
//
//                }
//                return Boolean.TRUE;
//            }
//            return Boolean.TRUE;
//        }
//        return Boolean.TRUE;
//    }


    @Transactional
    public Boolean parseToolInfoJson( List<Map<String, Object>> data , List<ToolForkInfoEntity> existEntities , List<String> partnos) {
        if(CollectionUtil.isEmpty(data)){
            return Boolean.TRUE;
        }
        List<ToolForkInfoEntity> insertList = new ArrayList<>();
        List<ToolForkInfoEntity> updateList = new ArrayList<>();
        data.forEach(paramMap -> {
            List<TypeItemEntity> typeItemEntity = typeItemRepository.selectParamsByTypeName((String) paramMap.get("type"));
            if (CollectionUtil.isEmpty(typeItemEntity) || Objects.isNull(typeItemEntity.get(0)) || StringUtil.isEmpty(typeItemEntity.get(0).getParams())) {
                //无对应分类记录
                return;
            }
            //利用反射获取字段处理基础参数
            String typeParam = typeItemEntity.get(0).getParams();
            String[] split = typeParam.split(",");
            List<String> stringList = Arrays.stream(split).collect(Collectors.toList());
            stringList.add("IIC");
            stringList.add("CCWS");
            stringList.add("CCMS");
            ToolForkInfoEntity toolForkInfoEntity = new ToolForkInfoEntity();
            //split = (String[]) stringList.toArray();
            stringList.forEach(s -> {
                String fileName = s.toLowerCase();
                try {
                    //获取所有字段
                    Field mappingFiled = toolForkInfoEntity.getClass().getDeclaredField(fileName);
                    //开启暴力反射，设置private修饰的字段值
                    mappingFiled.setAccessible(true);
                    //反射调用set方法
                    mappingFiled.set(toolForkInfoEntity, convertType(mappingFiled.getType().toString(), (String) paramMap.get(s)));
                    //将参数全部放入paramMap中
                    //paramMap.remove(split[i]);
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    log.error(e.getMessage());
                }
            });
            toolForkInfoEntity.setType(typeItemEntity.get(0).getType());
            //存入原始数据
            toolForkInfoEntity.setOriginalParams(JSONObject.toJSONString(paramMap));
            List<Map<String, Object>> paramList = new ArrayList<>();
            //处理完的基础信息map全作为json字段存入t_tool_fork_info的params字段
            paramMap.forEach((s, o) -> {
                HashMap<String, Object> paramsMap = new HashMap<>();
                paramsMap.put("nameEn", s);
                paramsMap.put("value", o);
                paramList.add(paramsMap);
            });
            toolForkInfoEntity.setParameters(JSONArray.toJSONString(paramList));
            List<ToolForkInfoEntity> filterList = existEntities.stream()
                    .filter(existToolForkInfoEntity -> existToolForkInfoEntity.getPartno().equals(paramMap.get("PARTNO")))
                    .collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(filterList) && filterList.size() == 1){
             //更新的数据
                toolForkInfoEntity.setId(filterList.get(0).getId());
                updateList.add(toolForkInfoEntity);
            }
            //所包含的不包括改物料编码则新增
            if(!partnos.contains(toolForkInfoEntity.getPartno())){
                insertList.add(toolForkInfoEntity);
            }
        });
        if (CollectionUtil.isNotEmpty(insertList)) {
            for (int i = 0; i < 20; i++) {
                List<ToolForkInfoEntity> subInsertList = insertList.stream().skip(i * 300).limit(300).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(subInsertList)) {
                    toolForkInfoMapper.insertBatchSomeColumn(subInsertList);
                }
            }
            //toolForkInfoMapper.insertBatchSomeColumn(insertList);
        }
        if (CollectionUtil.isNotEmpty(updateList)) {
            for (int i = 0; i < 60; i++) {
                List<ToolForkInfoEntity> subInsertList = updateList.stream().skip(i * 20).limit(50).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(subInsertList)) {
                    toolForkInfoMapper.updateBatchById(subInsertList);
                }
            }
            //toolForkInfoMapper.updateBatchById(updateList);
        }
        return Boolean.TRUE;
    }

    private static Object convertType(String type, String value) {
        if (Integer.class.getName().equals(type) || "int".equals(type)) {
            return Integer.valueOf(value);
        } else if (Double.class.getName().equals(type) || "double".equals(type)) {
            return Double.valueOf(value);
        } else if (Long.class.getName().equals(type) || "long".equals(type)) {
            return Long.valueOf(value);
        } else if (BigDecimal.class.toString().equals(type) || "bigDecimal".equals(type)) {
            if ("".equals(value) || StringUtil.isEmpty(value) || ObjectUtil.isNull(value)) {
                return new BigDecimal("0");
            }
            try {
                return new BigDecimal(value);
            } catch (NumberFormatException e) {
                return new BigDecimal("0");
            }
        } else {
            return value;
        }
    }

    public List<TypeItemEntity> updateCategoryList() {
        //1.比较树结构 整理出每个节点下缺少的子节点数据
        String s1 = CommonConstant.USAGE_ADRESS +  "/ZeusoftWebService.svc/api/GetCategoryList";
        List<CategoryVo> data = CommonUtil.getDataReload(s1);
        Map<String, List<CategoryVo>> interfaceCateGroupMap = new HashMap<>();
        Map<String, List<String>> interfaceGroupMap = new HashMap<>();
        Map<String, List<TypeItemVo>> dataBaseCateGroupMap = new HashMap<>();
        Map<String, List<String>> dataBaseGroupMap = new HashMap<>();
        List<TypeItemVo> filterList = new ArrayList<>();
        List<TypeItemEntity> insertList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(data)){
            //获取接口节点map
            data.forEach(categoryVo -> {
                if(StringUtils.isBlank(categoryVo.getLabel_parentNode())){
                    categoryVo.setLabel_parentNode("刀具库");
                }
            });
            interfaceCateGroupMap = data.stream().collect(Collectors.groupingBy(CategoryVo::getLabel_parentNode));
            interfaceGroupMap = interfaceCateGroupMap
                    .entrySet()
                    .stream()
                    .collect(Collectors.toMap(Map.Entry::getKey ,  value->value.getValue().stream().map(CategoryVo::getPartClass).collect(Collectors.toList())));
            //获取数据库节点map
            List<TypeItemVo> typeItemEntities = typeItemRepository.selectAll();
            dataBaseCateGroupMap = typeItemEntities.stream().collect(Collectors.groupingBy(TypeItemVo::getParentTypeName));
            dataBaseGroupMap = dataBaseCateGroupMap
                    .entrySet()
                    .stream()
                    .collect(Collectors.toMap(Map.Entry::getKey ,  value->value.getValue().stream().map(TypeItemVo::getTypeName).collect(Collectors.toList())));
            if(CollectionUtil.isNotEmpty(dataBaseGroupMap)){
                for (Map.Entry<String, List<String>> entry : dataBaseGroupMap.entrySet()) {
                    String key = entry.getKey();
                    List<String> dataList = entry.getValue();
                    List<String> interfaceList = interfaceGroupMap.getOrDefault(key, new ArrayList<>());
                    if(CollectionUtil.isNotEmpty(interfaceList)){
                        List<String> filters = interfaceList.stream().filter(s -> !dataList.contains(s)).collect(Collectors.toList());
                        if(CollectionUtil.isNotEmpty(filters)){
                            for (String filter : filters) {
                                TypeItemVo typeItemVo = new TypeItemVo();
                                typeItemVo.setTypeName(filter);
                                typeItemVo.setParentTypeName(key);
                                filterList.add(typeItemVo);
                            }
                        }
                    }
                }
            }
        }
        //根据差异list数据构建子节点插入数据
        if(CollectionUtil.isNotEmpty(filterList)){
            for (int i = 0; i < filterList.size(); i++) {
                TypeItemVo typeItemVo = filterList.get(i);
                TypeItemEntity childTypeItem = typeItemRepository.selectMaxChildTree(typeItemVo.getParentTypeName());
                TypeItemEntity typeItemEntity = new TypeItemEntity();
                if(ObjectUtil.isNotNull(childTypeItem)){
                    typeItemEntity.setOrderNum(childTypeItem.getOrderNum()+i+1);
                    typeItemEntity.setTypeName(typeItemVo.getTypeName());
                    typeItemEntity.setType(generateTypeCode(childTypeItem.getType() , i+1));
                    typeItemEntity.setParentId(childTypeItem.getParentId());
                    typeItemEntity.setParams(childTypeItem.getParams());
                    typeItemEntity.setSearchParams(childTypeItem.getSearchParams());
                    insertList.add(typeItemEntity);
                }else{
                    TypeItemEntity parentTypeItem = typeItemRepository.selectByTypeName(typeItemVo.getParentTypeName());
                    typeItemEntity.setOrderNum(1);
                    typeItemEntity.setTypeName(typeItemVo.getTypeName());
                    typeItemEntity.setType(generateTypeCodeReload(parentTypeItem.getType()));
                    typeItemEntity.setParentId(parentTypeItem.getId());
                    typeItemEntity.setParams(parentTypeItem.getParams());
                    typeItemEntity.setSearchParams(parentTypeItem.getSearchParams());
                    insertList.add(typeItemEntity);
                }
            }
        }
        if(CollectionUtil.isNotEmpty(insertList)){
            typeItemMapper.insertBatchSomeColumn(insertList);
        }
        return insertList;
    }

    private String generateTypeCodeReload(String type) {
        String letter = type.substring(type.length()-4 , type.length()-3);
        String suffix = "";
        for (char c :letter.toCharArray()){
            suffix = String.valueOf((char)(c + 1)) + "001";
        }
        return type + suffix;
    }

    private String generateTypeCode(String type , Integer integer) {
        String suffix = type.substring(type.length() - 3);
        String prefix = type.substring(0 ,type.length() - 3);
        return !suffix.startsWith("0")?  prefix + (Integer.parseInt(suffix)+integer) : prefix + "0" + (Integer.parseInt(suffix)+integer);
    }
}
